package main

import (
	"fmt"
	"github.com/salviati/go-qt5/qt5"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

var (
	exit = make(chan bool)
)

func main() {
	qt5.Main(func() {
		go ui_main()
		qt5.Run()
		exit <- true
	})
}

func ui_main() {
	w := qt5.NewWidget()
	w.SetWindowTitle("RemastersysQT配置文件选择器") //设置窗口标题
	w.SetSizev(450, 200)                     //设置窗口大小

	//==================== VBox 1 ====================

	vbox1 := qt5.NewVBoxLayout() //创建一个竖向排列的容器

	lbl1 := qt5.NewLabelWithText("未选择：")
	list1 := qt5.NewListWidget()

	root := os.Getenv("HOME") + "/.config/"
	i := strings.Count(root, "/")
	filepath.Walk(root,
		func(path string, info os.FileInfo, err error) error {
			if path != root && info.IsDir() && strings.Count(path, "/") == i {
				list1.AddItem(qt5.NewListWidgetItemWithText(info.Name()))
				fmt.Println("已添加：", info.Name())
			}
			return nil
		})

	vbox1.AddWidget(lbl1) //向容器内添加控件
	vbox1.AddWidget(list1)

	//==================== VBox 2 ====================

	vbox2 := qt5.NewVBoxLayout() //创建一个竖向排列的容器

	list2 := qt5.NewListWidget()
	lbl2 := qt5.NewLabelWithText("已选择：")

	vbox2.AddWidget(lbl2)
	vbox2.AddWidget(list2)

	//==================== HBox 1 ====================

	hbox1 := qt5.NewHBoxLayout() //创建一个横向排列的容器

	hbox1.AddLayout(vbox1) //向容器内添加容器
	hbox1.AddLayout(vbox2)

	//==================== VBox 3 ====================

	vbox3 := qt5.NewVBoxLayout() //创建一个竖向排列的容器

	btn1 := qt5.NewButtonWithText("将选中配置文件设置为系统默认")

	vbox3.AddLayout(hbox1)
	vbox3.AddWidget(btn1)

	//==================== BOX END ====================

	list1.OnItemDoubleClicked(func(*qt5.ListWidgetItem) {
		list2.AddItem(qt5.NewListWidgetItemWithText(list1.CurrentItem().Text()))
		list1.TakeItem(list1.CurrentRow())
	})

	list2.OnItemDoubleClicked(func(*qt5.ListWidgetItem) {
		list1.AddItem(qt5.NewListWidgetItemWithText(list2.CurrentItem().Text()))
		list2.TakeItem(list2.CurrentRow())
	})

	btn1.OnClicked(func() {
		fmt.Println(list2.Count())
		t := `#!/bin/bash
rm RemastersysQT.sh
echo 请输入密码
`
		c := list2.Count()
		for i := 0; i < c; i++ {
			t = t + `sudo cp -r $HOME/.config/` + list2.Item(i).Text() + ` /etc/skel/.config
echo 正在复制 $HOME/.config/` + list2.Item(i).Text() + ` 到 /etc/skel/.config/` + list2.Item(i).Text() + `
`
		}
		t = t + `echo 执行完毕，按回车结束
read anykey`
		ioutil.WriteFile("RemastersysQT.sh", []byte(t), 0644) //保存数据到文件
		cmd := exec.Command("exo-open", "--launch", "TerminalEmulator", "sh", `RemastersysQT.sh`)
		err := cmd.Start()
		if err != nil {
			fmt.Println(err)
		}
	})

	w.SetLayout(vbox3)

	defer w.Close()
	w.Show()
	<-exit
}
